package cn.com.libertymutual.core.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * 汉字转换为拼音
 * @author Red
 */
public class PinYinUtils {
	/**
	 * 测试main方法
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(ToFirstChar("农业银行.金穗通宝贵宾卡（白金）").toUpperCase()); // 转为首字母大写
		System.out.println(ToPinyinByBank("农业银行.金穗通宝贵宾卡（白金）"));
	}

	/**Remarks: 汉字转为全拼音——银行版<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年12月7日下午6:00:34<br>
	 * Project：liberty_sale_plat<br>
	 * @param chinese
	 * @return
	 */
	public static String ToPinyinByBank(String chinese) {
		String py = PinYinUtils.ToPinyin(chinese);
		py = StringUtils.isNotBlank(py) ? py.replaceAll("yinxing", "yinhang") : "other";
		return py;
	}

	/**
	 * 获取字符串每个汉字的拼音首字母
	 * @param chinese
	 * @return
	 */
	public static String ToFirstChar(String chinese) {
		String pinyinStr = "";
		try {
			char[] newChar = chinese.toCharArray(); // 转为单个字符
			HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
			defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
			defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			for (int i = 0; i < newChar.length; i++) {
				if (newChar[i] > 128) {
					String[] strings = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat);
					pinyinStr += CollectionUtils.sizeIsEmpty(strings) ? "" : strings[0].charAt(0);
				} else {
					pinyinStr += newChar[i];
				}
			}
		} catch (Exception e) {
			System.out.println("获取字符串每个汉字的拼音首字母异常：" + e.toString());
		}
		return pinyinStr;
	}

	/**
	 * 汉字转为全拼音
	 * @param chinese
	 * @return
	 */
	public static String ToPinyin(String chinese) {
		String pinyinStr = "";
		try {
			if (StringUtils.isNotBlank(chinese)) {
				chinese = chinese.replaceAll(" ", "");
			}

			char[] newChar = chinese.toCharArray();
			HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
			defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
			defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			for (int i = 0; i < newChar.length; i++) {
				if (newChar[i] > 128) {
					String[] strings = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat);
					pinyinStr += CollectionUtils.sizeIsEmpty(strings) ? "" : strings[0];
				} else {
					pinyinStr += newChar[i];
				}
			}
		} catch (Exception e) {
			System.out.println("汉字转为全拼音异常：" + e.toString());
		}
		return pinyinStr.toLowerCase();
	}
}